package com.learning.test.config;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

  @Bean
  SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
      .csrf(Customizer.withDefaults()) // 跨站请求伪造漏洞防护过滤器
      .authorizeHttpRequests(authorize -> authorize // 权限管理
          .requestMatchers("/admin").hasRole("ADMIN") // 访问admin页面需要ADMIN角色
          .requestMatchers("/user").hasRole("USER") // 访问user页面需要USER角色
          .anyRequest().authenticated()
      )
      .httpBasic(Customizer.withDefaults()) // 基础HTTP认证，无状态
      .formLogin(Customizer.withDefaults()); // 基于登录的认证，基于会话
    return http.build();
  }
  
  
   @Bean
   UserDetailsManager users(DataSource dataSource) {
     // 创建一个加密器
     PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
     
     UserDetails user = User.builder()
       .username("xiaolan")
       .password(encoder.encode("123")) // 加密保存
       .roles("USER")
       .build();
     JdbcUserDetailsManager users = new JdbcUserDetailsManager(dataSource);
     // 若用户不存在则创建
     if(!users.userExists("xiaolan")) {
       users.createUser(user);
     }
     return users;
   }
}
